//
//  DXTabBar.swift
//  weiBoOfSwift
//
//  Created by simon on 15/12/5.
//  Copyright © 2015年 simon. All rights reserved.
//

import UIKit

class DXTabBar: UITabBar {

    
    // MARK: - 注意闭包的循环引用
//    设置回调闭包
    var compseBtnClickClosure:(()->())?
    
    // MARK: - 懒加载composeBtn
    lazy var composeBtn:UIButton = {
    
    let composeBtn = UIButton.init()
        composeBtn.addTarget(self, action: "compseBtnClick", forControlEvents:.TouchUpInside)
//        设置背景图片
    composeBtn.setBackgroundImage(UIImage.init(named: "tabbar_compose_button_highlighted"), forState: .Highlighted)
    composeBtn.setBackgroundImage(UIImage.init(named: "tabbar_compose_button"), forState: .Normal)
//        设置图片
    composeBtn.setImage(UIImage.init(named: "tabbar_compose_icon_add_highlighted"), forState: .Highlighted)
    composeBtn.setImage(UIImage.init(named: "tabbar_compose_icon_add"), forState: .Normal)
//        自动布局宽高
     composeBtn.sizeToFit()
    return composeBtn
    }()


    // MARK: - composeBtn点击事件
  @objc private  func compseBtnClick(){
        
//        logPrint("compseBtnClick")
    
        if let closure = compseBtnClickClosure{
        closure()
        }
    }
    
    // MARK: - 重写init方法
    override init(frame: CGRect) {
        super.init(frame: frame)
//        添加到self中
        addSubview(composeBtn)
    }
//      重置从XIB中加载无效
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
//     重写layoutSuviews布局子控件
    override func layoutSubviews() {
        super.layoutSubviews()
        //       设置composeBtn的位置
        composeBtn.center = CGPoint.init(x: frame.width * 0.5, y: frame.height * 0.5)
//        调整子控件的位置
        let tabarW = frame.width/5
        var i = 0
        for  sub in subviews{
//         当子控件为 UITabBarButton时
            if sub.isKindOfClass(NSClassFromString("UITabBarButton")!){
                var subFrame = sub.frame
                
                subFrame.size.width = tabarW
                
                subFrame.origin.x = CGFloat(i) * tabarW
                
                sub.frame = subFrame
                   i++
                if i == 2{
                    i++
                }
             
            }
            
        }
    }
    
    
}
